package cn.tedu.egmvc3.controller;

import cn.tedu.egmvc3.base.response.JsonResult;
import cn.tedu.egmvc3.base.response.StatusCode;
import cn.tedu.egmvc3.mapper.UserMapper;
import cn.tedu.egmvc3.pojo.dto.UserAddParam;
import cn.tedu.egmvc3.pojo.dto.UserUpdateParam;
import cn.tedu.egmvc3.pojo.entity.User;
import cn.tedu.egmvc3.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;
@Slf4j
@Api(tags = "01.用户管理模块")
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("add")
    @ApiOperation(value = "1.用户添加")
    @ApiOperationSupport(order = 100)
    public JsonResult add(UserAddParam userAddParam){
        log.debug("userAddParam = " + userAddParam);
        User user = new User();
        BeanUtils.copyProperties(userAddParam,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int i = userMapper.insert(user);
        if(i>0){
            return JsonResult.ok();
        }else{
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }
    @GetMapping("list")
    @ApiOperation(value = "2.用户列表")
    @ApiOperationSupport(order = 200)
    public JsonResult list(){
        List<UserListVO> userListVOS = userMapper.list();
        log.debug("userListVOS = " + userListVOS);
        return JsonResult.ok(userListVOS);
    }
    @PostMapping("del")
    @ApiOperation(value = "3.用户删除")
    @ApiOperationSupport(order = 300)
    public JsonResult del(@PathVariable Long id){
        if(id<0){
            throw new IllegalArgumentException("id值非法!");
        }
        log.debug("id = " + id);
        int i = userMapper.del(id);
        if(i>0){
            return JsonResult.ok();
        }else{
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }
    @PostMapping("update")
    @ApiOperation(value = "4.用户更新")
    @ApiOperationSupport(order = 400)
    public JsonResult update(@ApiIgnore UserUpdateParam userUpdateParam){
        log.debug("userUpdateParam = " + userUpdateParam);
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam,user);
        user.setUpdateTime(new Date());
        int i = userMapper.update(user);
        if(i>0){
            return JsonResult.ok();
        }else{
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }
}
